package org.fcy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.fcy.domain.po.Result;
import org.fcy.domain.po.User;
import org.fcy.mapper.UserMapper;
import org.fcy.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.fcy.utils.JwtUtil;
import org.fcy.utils.Md5Util;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 用户基本信息表 服务实现类
 * </p>
 *
 * @author fcy
 * @since 2025-10-27
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    private final UserMapper userMapper;
    private final StringRedisTemplate stringRedisTemplate;
    /**
     * 用户注册
     *
     * @param username 用户名
     * @param password 密码
     * @return
     */
    @Override
    public Result<String> register(String username, String password) {
        String md5Password = Md5Util.getMD5String(password);
        User user = new User();
        user.setUsername(username);
        user.setPasswordHash(md5Password);
        user.setEmail("");
        userMapper.insert(user);
        log.info("用户注册成功");
        return Result.success("注册成功");

    }
    /**
     * 用户登录
     *
     * @param username 用户名
     * @param password 密码
     * @return
     */
    @Override
    public Result<String> login(String username, String password) {
        //判断用户名是否存在
        QueryWrapper<User> wrapper = new QueryWrapper<org.fcy.domain.po.User>()
                .eq("username",username);
        User user = userMapper.selectOne(wrapper);
        if(user==null){
            return Result.error("用户名不存在");
        };
        if(!Md5Util.checkPassword(password,user.getPasswordHash())){
            return Result.error("密码错误");
        };
        //生成 token
        Map<String, Object> claims=new HashMap<>();
        claims.put("id", user.getUserId());
        claims.put("username", user.getUsername());
        String token = JwtUtil.genToken(claims);
        log.info("用户登录成功");
        //存入redis
        stringRedisTemplate.opsForValue().set(token,token,12, TimeUnit.HOURS);
        return Result.success(token);
    }
}
